<template>
  <!-- 业务组件配置管理 -->
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar :add-active="addActive" :del-active="delActive" :cancel-active="cancelActive" :has-edit="false" :has-del="false" :has-save="false" :has-add="true" :save-active="saveActive" @add="add" @cancel="cancel" @del="del" />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label">诊断项名称:</div>
          <div class="input">
            <el-input v-model="diseaseName" placeholder="请输入诊断项名称" clearable @input="search()" />
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <!-- 业务组件展示表格 -->
      <el-tabs type="border-card" v-model="activeName" @tab-click="handletabClick">
        <el-tab-pane label="已审核" name="1">
          <!-- 业务组件展示表格 -->
          <div class="zh-table-view">
            <el-table :data="tableData" @row-click="handleEdit" height="100%">
              <el-table-column type="index" label="序号" width="55" align="center" />
              <el-table-column prop="caseName" label="案例名称">
                <template slot-scope="scope">
                  <div class="ellipsis" :title="scope.row.caseName">{{ scope.row.caseName }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="diseaseName" label="疾病名称" />
              <el-table-column prop="organizationName" label="案例来源" />
              <el-table-column prop="regionName" label="来源地区" />
              <el-table-column prop="provinceName" label="来源省" />
              <el-table-column prop="cityName" label="来源市" />
              <el-table-column prop="areaName" label="来源区" />
              <el-table-column prop="therapeuticMethod" label="治疗方法">
                <template slot-scope="scope">
                  <div class="ellipsis" :title="scope.row.therapeuticMethod">{{
        scope.row.therapeuticMethod }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="preventionMethod" label="预防方法">
                <template slot-scope="scope">
                  <div class="ellipsis" :title="scope.row.preventionMethod">{{
        scope.row.preventionMethod }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="疾病症状">
                <template slot-scope="scope">
                  <div class="ellipsis" :title="scope.row.mainSymptoms">{{ scope.row.mainSymptoms }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="案例图片" width="130">
                <template slot-scope="scope">
                  <el-image v-if="scope.row.imgList && scope.row.imgList.length > 0" class="imageStyle" :src="scope.row.imgList[0]" :preview-src-list="scope.row.imgList">
                  </el-image>
                  <span v-else>暂无图片</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" @click="edit">修改</el-button>
                  <el-button size="mini" type="warning" @click="dellineallmes(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="待审核" name="2">
          <!-- 业务组件展示表格 -->
          <div class="zh-table-view">
            <el-table :data="tableData" @row-click="handleEdit" height="100%">
              <el-table-column type="index" label="序号" width="55" align="center" />
              <el-table-column prop="caseName" label="案例名称">
                <template slot-scope="scope">
                  <div class="ellipsis" :title="scope.row.caseName">{{ scope.row.caseName }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="diseaseName" label="疾病名称" />
              <el-table-column prop="organizationName" label="案例来源" />
              <el-table-column prop="regionName" label="来源地区" />
              <el-table-column prop="provinceName" label="来源省" />
              <el-table-column prop="cityName" label="来源市" />
              <el-table-column prop="areaName" label="来源区" />
              <el-table-column prop="therapeuticMethod" label="治疗方法">
                <template slot-scope="scope">
                  <div class="ellipsis" :title="scope.row.therapeuticMethod">{{
        scope.row.therapeuticMethod }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="preventionMethod" label="预防方法">
                <template slot-scope="scope">
                  <div class="ellipsis" :title="scope.row.preventionMethod">{{
        scope.row.preventionMethod }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="疾病症状">
                <template slot-scope="scope">
                  <div class="ellipsis" :title="scope.row.mainSymptoms">{{ scope.row.mainSymptoms }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="案例图片" width="130">
                <template slot-scope="scope">
                  <el-image v-if="scope.row.imgList && scope.row.imgList.length > 0" class="imageStyle" :src="scope.row.imgList[0]" :preview-src-list="scope.row.imgList">
                  </el-image>
                  <span v-else>暂无图片</span>
                </template>
              </el-table-column>
              <el-table-column label="审核" width="200">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" v-show="scope.row.applyStatus == 1" @click="applyDiseaseCase(0, scope.row)">通过</el-button>
                  <el-button size="mini" type="primary" v-show="scope.row.applyStatus == 1" @click="applyDiseaseCase(2, scope.row)">不通过</el-button>
                  <span v-show="scope.row.applyStatus == 0">通过</span>
                  <span v-show="scope.row.applyStatus == 2">不通过</span>
                </template>
              </el-table-column>
            </el-table>
            <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
          </div>
        </el-tab-pane>
      </el-tabs>

    </template>

    <template v-slot:dialog>
      <!-- 新增业务组件的弹框 -->
      <el-dialog :title="titleText + '诊断项'" class="formData" :visible.sync="dialogFormVisible" width="80%" :before-close="() => { dialogFormVisible = false }">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="案例名称" prop="caseName" class="w100p">
                <el-input class="w100p" v-model="formData.caseName" clearable placeholder="请输入案例名称" />
              </el-form-item>
              <el-form-item label="选择疾病" prop="diseaseBankId" class="w100p">
                <el-select class="w100p" :disabled="nowChanceStau == 'edit'" v-model="formData.diseaseBankId" placeholder="请选择疾病" filterable clearable>
                  <el-option v-for="item, index in diseaseList" :key="index" :label="item.diseaseName" :value="item.diseaseBankId" />
                </el-select>
              </el-form-item>
              <el-form-item label="疾病症状" prop="mainSymptoms" class="w100p">
                <el-input class="w100p" v-model="formData.mainSymptoms" clearable type="textarea" :rows="2" placeholder="请输入特征描述" maxlength="300" show-word-limit />
              </el-form-item>
              <el-form-item label="预防方法" prop="preventionMethod" class="w100p">
                <el-input class="w100p" v-model="formData.preventionMethod" clearable type="textarea" :rows="2" placeholder="请输入特征描述" maxlength="300" show-word-limit />
              </el-form-item>
              <el-form-item label="治疗方法" prop="therapeuticMethod" class="w100p">
                <el-input class="w100p" v-model="formData.therapeuticMethod" clearable type="textarea" :rows="2" placeholder="请输入特征描述" maxlength="300" show-word-limit />
              </el-form-item>
              <el-form-item label="特征图片" prop="fileUrlList">
                <upload :limit="5" :urlList="formData.urlList" @getFile="getFile" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择坐标" class="w100p">
                <baidu-map v-if="resetMap" ref="myMap" class="map" :center="center" :zoom="zoom" :scroll-wheel-zoom="true" map-type="BMAP_HYBRID_MAP" @click="setCenterPoint" @load="handleMapLoad">
                  <bm-marker :position="{ lng: center.lng, lat: center.lat }" :dragging="false" />
                  <bm-control>
                    <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
                      <el-input v-model="keyword" type="text" placeholder="请输入地名关键字" style="background-color:#003947;" clearable>
                        <i slot="prefix" class="el-input__icon el-icon-search"></i>
                      </el-input>
                    </bm-auto-complete>
                  </bm-control>
                  <bm-local-search :keyword="keyword" :auto-viewport="true" :select-first-result="true" :panel="false" />
                </baidu-map>
                <div v-show="formData.regionName" style="text-align: left;">
                  {{ formData.regionName + formData.provinceName + formData.cityName +
                                    formData.areaName }}
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel('formData')">取 消</el-button>
          <el-button type="primary" @click="savemes">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import ActionBar from '@/components/ActionBar/index';
import { mymixin } from '@/utils/mixins';
import SearchBox from '@/components/SearchBox';
import BaseMainSlot from '@/components/BaseMainSlot/newBaseMainSlot.vue';
import zhreq from '@/api/basic-info-manage/disease-case-management';

import { addressList } from '@/utils/address_new';
import diseaseManagement from '@/api/basic-info-manage/disease-management';
import upload from '@/components/uploadimage/upload.vue';
import Pagination from '@/components/Pagination';
// import { getTitleList } from "@/components/getnameurl";
export default {
  components: { ActionBar, Pagination, BaseMainSlot, SearchBox, upload },
  mixins: [mymixin],
  data() {
    return {
      isshowuploadpic: false,
      tableData: [],
      resetMap: true,
      pageSize: 10,
      currentPage: 1,
      totalSize: 0,
      diseaseName: '',
      activeName: '1',
      formData: {},
      diseaseList: [],
      rules: {
        caseName: [{ required: true, message: '请输入', trigger: 'change' }],
        mainSymptoms: [{ required: true, message: '请选择', trigger: 'change' }],
        preventionMethod: [{ required: true, message: '请输入', trigger: 'change' }],
        therapeuticMethod: [{ required: true, message: '请输入', trigger: 'change' }],
        diseaseBankId: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      center: {},
      zoom: 22,
      Baidu_BMap: null,
      keyword: '',
      regionList: ['华北地区', '东北地区', '华东地区', '华中南地区', '西南地区', '西北地区', '特别地区']
    };
  },
  created() {
    this.initData();
  },
  watch: {
    dialogFormVisible() {
      setTimeout(() => {
        this.keyword = '';
        this.jumpToPoint();
        this.resetMap = false;
        this.$nextTick(() => {
          this.resetMap = true;
        });
      }, 1000);
    }
  },
  mounted() {
    this.gettabledataList();
  },
  methods: {
    // 获取下拉框信息
    async initData() {
      let { data: diseaseList } = await diseaseManagement.queryByCondition({});
      this.diseaseList = diseaseList;
    },
    handleMapLoad(e) {
      console.log(e);
      this.jumpToPoint();
    },
    jumpToPoint() {
      if (this.nowChanceStau == 'edit') {
        let { latitude, longitude } = JSON.parse(JSON.stringify(this.formData));
        console.log(this.formData);
        if (!longitude || !latitude) {
          this.center = { lng: 120.230648, lat: 30.811543 };
        } else {
          this.center = { lng: longitude || 120.230648, lat: latitude || 120.230648 };
        }
      } else {
        this.center = { lng: 120.230648, lat: 30.811543 };
      }
    },
    setCenterPoint(e) {
      let { point } = e;
      this.center.lng = point.lng;
      this.center.lat = point.lat;
      console.log(point);
      this.$set(this.formData, 'latitude', point.lat);
      this.$set(this.formData, 'longitude', point.lng);
      this.getAddress(point);
    },
    getAddress(p) {
      const BMap = window.BMap;
      const geocoder = new BMap.Geocoder();
      const point = new BMap.Point(p.lng, p.lat);
      const that = this;
      geocoder.getLocation(point, (result) => {
        if (result) {
          let provinceCode = that.findCodeByName(addressList, result.addressComponents.province);
          this.address = {
            provinceName: result.addressComponents.province,
            provinceCode: provinceCode,
            cityName: result.addressComponents.city,
            cityCode: that.findCodeByName(addressList, result.addressComponents.city),
            areaName: result.addressComponents.district,
            areaCode: that.findCodeByName(addressList, result.addressComponents.district),
            regionName: this.regionList[Number(provinceCode[0]) + 1],
            regionCode: provinceCode[0]
          };
          this.formData = {
            ...this.formData,
            ...this.address
          };
        } else {
          alert('无法获取地址信息');
        }
      });
    },
    findCodeByName(data, name) {
      for (const item of data) {
        if (item.name == name) {
          return item.code;
        }
        if (item.children) {
          const result = this.findCodeByName(item.children, name);
          if (result) {
            return result;
          }
        }
      }
      return null; // 如果没有找到，返回null
    },
    // 获取表格信息
    gettabledataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          diseaseName: this.diseaseName
        }
      };
      let api = zhreq.queryPageByCondition;
      if (this.activeName == 1) {
        api = zhreq.queryPageByCondition;
      } else {
        api = zhreq.queryPageByCondition_apply;
      }
      api(params)
        .then((res) => {
          let resData = res.data || {};
          if (res.code === 1) {
            this.tableData = resData.content || [];
            this.tableData.forEach((item) => {
              item.imgList = item.fileUrlList ? item.fileUrlList.split(',') : [];
            });
            this.totalSize = resData.totalElements;
            this.resetActionBar();
          } else {
            this.$message.warning('获取表格失败');
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handletabClick(e) {
      this.currentPage = 1;
      this.activeName = e.name;
      this.gettabledataList();
    },
    // 搜索
    search() {
      this.currentPage = 1;
      this.gettabledataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.gettabledataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.gettabledataList();
    },
    applyDiseaseCase(i, e) {
      console.log(i, e, 'i');
      let text = i == 2 ? '您确定不通过审核吗' : '您确定通过审核';
      if (i == 2) {
        this.$prompt(text, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /[^ \x20]+/,
          inputErrorMessage: '请输入不通过原因'
        })
          .then(({ value }) => {
            let params = {
              ...e,
              applyStatus: i,
              reason: value
            };
            zhreq.applyDiseaseCase(params).then((res) => {
              if (res.code === 1) {
                this.$message.success('操作成功！');
                this.gettabledataList();
              } else {
                this.$message.success('操作失败！');
              }
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '取消输入'
            });
          });
      } else {
        this.$confirm(text, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            zhreq
              .applyDiseaseCase({
                ...e,
                applyStatus: i
              })
              .then((res) => {
                if (res.code === 1) {
                  this.$message.success('操作成功！');
                  this.gettabledataList();
                } else {
                  this.$message.success('操作失败！');
                }
              });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
      }
    },
    // 删除一个业务组件
    dellineallmes(i, e) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          zhreq.delList([e.diseaseCaseId]).then((res) => {
            if (res.code === 1) {
              this.$message.success('删除成功！');
              this.gettabledataList();
            } else {
              this.$message.success('删除失败！');
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 上传图片
    getFile(file) {
      this.formData.urlList = file;
      this.formData.fileUrlList = file
        .map((e) => {
          return e.url;
        })
        .toString();
      console.log(this.formData);
    },
    handleEdit(row) {
      if (row) {
        this.formData = JSON.parse(JSON.stringify(row));
        this.formData.urlList = row.imgList.map((e) => {
          return { url: e };
        });
      }
    },
    // 保存要添加的业务的组件信息
    savemes() {
      this.formData.fileUrlList = this.formData.urlList
        ? this.formData.urlList
            .map((e) => {
              return e.url;
            })
            .toString()
        : '';
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === 'edit') {
            let param = {
              ...this.formData
            };
            zhreq.edit(param).then((response) => {
              let mes = response;
              if (mes.code === 1) {
                this.$message.success('修改成功！');
                this.gettabledataList();
                this.cancel('formData');
              } else {
                this.$message.warning(mes.msg || '操作失败！');
              }
            });
          } else if (this.nowChanceStau === 'add') {
            let param = {
              ...this.formData
            };
            zhreq.add(param).then((response) => {
              let mes = response;
              if (mes.code === 1) {
                this.$message.success('添加成功！');
                this.gettabledataList();
                this.cancel('formData');
              } else {
                this.$message.warning(mes.msg || '操作失败！');
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import '~@/styles/variables.scss';

.imageStyle {
  height: 100px;
  width: 100px;
  border-radius: 4px;
}

.ellipsis {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  /* 限制在三行内 */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.map {
  height: 400px;
  width: 100%;
}

::v-deep .el-tab-pane {
  height: 100%;
}

::v-deep .el-form-item__label {
  min-width: 140px !important;
}

::v-deep .el-tabs--border-card {
  background-color: #00000000;
  border: 1px solid #255064;
  height: 100%;
}

::v-deep .el-tabs--border-card > .el-tabs__header {
  background-color: #00000000;
  border-bottom: 1px solid #255064;
}

::v-deep .el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active {
  background: #255064;
  color: #ffffff;
  border-right: 0;
  border-left: 0;
}

::v-deep .el-tabs__content {
  height: calc(100% - 60px);
}
</style>